package com.yunhe.fineart;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.yunhe.fineart.utils.Utils;
import com.yunhe.fineart.view.GraffitiView;
import com.yunhe.fineart.view.GridRelativeLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.plugin.common.MethodChannel;
import lombok.AllArgsConstructor;
import lombok.Data;
import me.panpf.sketch.SketchImageView;

public class CourseActivity extends Activity {
    String TAG = getClass().getSimpleName();


    private SketchImageView imageView;
    private int rotate_idx = 0;
    LinearLayout line_container, line_bottom;
    GridRelativeLayout gd;
    Map<String, String> operation = new HashMap<>();

    private Gson gson = new Gson();

    private Handler handler = new Handler();
    private Runnable runnable = null;

    boolean rotating = false;
    boolean exiting = false;

    GraffitiView graffitiView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_course);

        buildScreen();

        imageView = findViewById(R.id.courseImage);
        graffitiView = findViewById(R.id.graffitiView);


        gd = findViewById(R.id.grid_rel);
        line_container = findViewById(R.id.ling_container);
        line_bottom = findViewById(R.id.ling_bottom);
        imageView.setShowDownloadProgressEnabled(true);
        imageView.setZoomEnabled(true);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (line_container.getVisibility() == View.VISIBLE)
                {
                    line_container.setVisibility(View.GONE);
                }
                else
                {
                    line_container.setVisibility(View.VISIBLE);
                }
            }
        });
        imageView.getZoomer().addOnMatrixChangeListener(imageZoomer -> {

            if (runnable != null) handler.removeCallbacks(runnable);
            runnable = () -> {
                if (rotating) return;
                if (exiting) return;
                float min = imageView.getZoomer().getMinZoomScale();
                float max = imageView.getZoomer().getMaxZoomScale();
                float scale = imageView.getZoomer().getZoomScale();
                RectF rect = new RectF();
                imageView.getZoomer().getDrawRect(rect);
                Rect drawingRect = new Rect();
                imageView.getDrawingRect(drawingRect);
                MatrixOperation mo = new MatrixOperation(scale, min, max, rect.left, rect.top, drawingRect.width());
                String matrix = gson.toJson(mo);
                sendOperation("matrix", matrix);
            };
            handler.postDelayed(runnable, 500);
        });

        String url = getIntent().getStringExtra("url");
        if (url != null) {
            Toast.makeText(this, "url=" + url, Toast.LENGTH_LONG);
            imageView.displayImage(url);
        }

        addTextItem();

        sendOperation("original", "on");

        exiting = false;

        FrameLayout rootLayout = findViewById(R.id.rootLayout);
        rootLayout.setOnClickListener(view -> {
            if (line_container.getVisibility() == View.VISIBLE)
            {
                line_container.setVisibility(View.GONE);
            }
            else
            {
                line_container.setVisibility(View.VISIBLE);
            }
        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void sendOperation(String oper, String value) {
        operation.clear();
        operation.put("oper", oper);
        operation.put("value", value);
        MainActivity.methodChannel.invokeMethod("courseOperation", operation, new MethodChannel.Result() {
            @Override
            public void success(@Nullable Object result) {
                int code = (int) result;
                if (code != 200)
                    Toast.makeText(CourseActivity.this, code + "", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {

            }

            @Override
            public void notImplemented() {

            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        if (height > width) {
            height = width * 1080 / 1920;
        } else {
            width = height * 1920 / 1080;
        }

        Utils.setViewLayoutParams(imageView, width, height);
        Utils.setViewLayoutParams(graffitiView,width,height);
        Log.d("Native", "==>width:" + width + "   height:" + height);
    }

    public void onBack(View view) {
        Log.i(TAG, "onBack");
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        exiting = true;
        sendOperation("finishcourse", "yes");
        finish();
        ///super.onBackPressed();
    }

    List<TextView> textViewList = new ArrayList<>();
    String[] titles = {"原图", "网格", "黑白", "旋转", "讲解"};
    boolean isGrid;
    boolean isExplain;

    void addTextItem() {
        for (int i = 0; i < titles.length; i++) {
            TextView tv = new TextView(this);

            textViewList.add(tv);
            tv.setText(titles[i]);
            tv.setGravity(Gravity.CENTER_VERTICAL);
            tv.setTag(i);
            tv.setTextSize(16);

            if (i == 2 || i == 4)
            {
                tv.setTextColor(Color.DKGRAY);
                tv.setOnClickListener(null);
            }
            else
            {
                tv.setTextColor(getResources().getColor(R.color.white));
                tv.setOnClickListener(tvClick);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
            line_container.addView(tv, lp);
        }


    }

    int lastPos;
    boolean isBlackWhite;
    ColorMatrixColorFilter filter;
    int width;
    int height;

    void buildScreen() {
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        width = dm.widthPixels;
        height = dm.heightPixels;
        Log.i("course", "w:" + width + " h:" + height);
    }

    View.OnClickListener tvClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = (int) v.getTag();
            lastPos = id;
            refreshTv();
            rotating = false;
            switch (id) {
                case 0:
                    if (isGrid) {
                        gd.clearLine();
                    }
                    if (isBlackWhite) {
                        imageView.setColorFilter(null); // 如果想恢复彩色显示，设置为null即可
                    }

                    if (rotate_idx > 0) {
                        rotate_idx = 0;
                    }
                    imageView.getZoomer().rotateTo(rotate_idx * 90);
                    sendOperation("original", "on");
                    break;
                case 1:
                    isGrid = !isGrid;
                    if (isGrid) {
                        gd.setInf(5, 5, width, height);//画网格线
                    } else {
                        gd.clearLine();
                    }
                    sendOperation("grid", isGrid ? "on" : "off");
                    break;
                case 2:
                    isBlackWhite = !isBlackWhite;
                    if (isBlackWhite) {
                        imageView.setColorFilter(getFilter()); // 如果想恢复彩色显示，设置为null即可
                    } else {
                        imageView.setColorFilter(null);
                    }
                    sendOperation("blackwhite", isBlackWhite ? "on" : "off");
                    break;
                case 3:
                    rotating = true;
                    if (++rotate_idx == 4) rotate_idx = 0;
                    imageView.getZoomer().rotateTo(rotate_idx * 90);
                    sendOperation("rotate", (rotate_idx * 90) + "");
                    break;
                case 4:
                    isExplain = !isExplain;
                    int visibility = isExplain ? View.VISIBLE : View.INVISIBLE;
//                    line_bottom.setVisibility(visibility);
                    graffitiView.setVisibility(visibility);
                    if (isExplain) {
                        graffitiView.startSend();
                    } else {
                        graffitiView.stopSend();
                    }

                    break;
            }
        }
    };


    public ColorMatrixColorFilter getFilter() {
        if (filter == null) {
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(0); // 设置饱和度
            filter = new ColorMatrixColorFilter(cm);
        }
        return filter;
    }

    void refreshTv() {
        for (int i = 0; i < titles.length; i++) {
            TextView tv = textViewList.get(i);
            int color = (i == lastPos) ? getResources().getColor(R.color.red) : getResources().getColor(R.color.white);

            if (i == 2 || i == 4) color = Color.DKGRAY;

            tv.setTextColor(color);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            rotating = false;
        }
        boolean result = true;
        try {
            result = super.dispatchTouchEvent(ev);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Data
    @AllArgsConstructor
    class ScaleOperation {
        float scale;
        float top;
        float left;
        float width;
        float focusX;
        float focusY;
        boolean drag;
    }

    @Data
    @AllArgsConstructor
    public class MatrixOperation {
        float scale;
        float mins;
        float maxs;
        float left;
        float top;
        float width;
    }
}